package com.travel.server.manager.impl.command.adversiting;

import com.travel.common.util.CollectionUtil;
import com.travel.server.manager.dto.request.advertising.QueryAdvertisingSourceListRequest;
import com.travel.server.manager.dto.response.advertising.QueryAdvertisingSourceListResponse;
import com.travel.server.manager.dto.response.advertising.QueryAdvertisingSourceListResponse.SourceItem;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.PageDto;
import com.travel.server.manager.impl.dal.PositionDal;
import com.travel.server.manager.impl.dal.SourceDal;
import com.travel.server.manager.model.AdvertisingSourceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: LiZhenhui
 * @Date: 2018/12/20 15:32
 * @Desc:
 */
@Component
@Slf4j
public class QueryAdvertisingSourceListCommand extends AbstractCommand<QueryAdvertisingSourceListRequest, QueryAdvertisingSourceListResponse> {

    @Autowired
    private SourceDal sourceDal;

    @Autowired
    private PositionDal positionDal;

    @Override
    protected void checkInput(QueryAdvertisingSourceListRequest request) {
        checkPageInput(request);
    }

    @Override
    public QueryAdvertisingSourceListResponse handle(QueryAdvertisingSourceListRequest request) {
        checkInput(request);

        QueryAdvertisingSourceListResponse response = new QueryAdvertisingSourceListResponse();
        List<SourceItem> sourceList = new ArrayList<>();
        PageDto<AdvertisingSourceInfo> pageDto = sourceDal.selectByPage(request.getOffset(), request.getLimit());
        response.setTotalNum(pageDto.getTotal());
        List<AdvertisingSourceInfo> list = pageDto.getList();
        if(CollectionUtil.isEmpty(list)){
            response.setSourceList(sourceList);
            return response;
        }

        List<Integer> positionIdList = new ArrayList<>();
        for(AdvertisingSourceInfo info : list){
            positionIdList.add(info.getPositionId());
        }

        Map<Integer, String> positionInfoMap = positionDal.makeMap(positionIdList);

        for(AdvertisingSourceInfo info : list){
            SourceItem item = new SourceItem();
            item.setHyperLink(info.getHyperLink());
            item.setId(info.getId());
            item.setPositionId(info.getPositionId());
            item.setPositionName(positionInfoMap.get(info.getPositionId()));
            item.setSort(info.getSort());
            item.setTitle(info.getSourceTitle());
            item.setType(info.getSourceType());
            item.setUrl(info.getUrl());
            sourceList.add(item);
        }
        response.setSourceList(sourceList);

        return response;
    }
}
